package com.changgou.search.controller;

import com.changgou.entity.Page;
import com.changgou.search.feign.SkuFeign;
import com.changgou.search.pojo.SkuInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Map;

@Controller
@RequestMapping(value = "/search")
public class SearchController {

    @Autowired
    private SkuFeign skuFeign;

    /**
     * 搜索
     *
     * @param searchMap
     * @return
     */
    @GetMapping(value = "/list")
    public String search(@RequestParam(required = false) Map searchMap, Model model) {
        //调用changgou-service-search微服务
        Map<String, Object> resultMap = skuFeign.search(searchMap);
        //搜索结果
        model.addAttribute("result", resultMap);
        //搜索条件
        model.addAttribute("searchMap", searchMap);

        //请求url
        String url = url(searchMap);
        model.addAttribute("url", url);
        //总记录数
        long totalElements = Long.parseLong(resultMap.get("totalElements").toString());
        //当前页
        int currentPage = Integer.valueOf(resultMap.get("pageNum").toString());
        //页面大小
        int pageSize = Integer.valueOf(resultMap.get("pageSize").toString());


        //页面大小


        Page<SkuInfo> page = new Page<>(totalElements, currentPage, pageSize);
        model.addAttribute("page", page);

        return "search";
    }

    //url组装 和 处理
    private String url(Map<String, String> searchMap) {
        // URL 地址
        String url = "/search/list";
        if (searchMap != null && searchMap.size() > 0) {
            url += "?";
            for (Map.Entry<String, String> entry : searchMap.entrySet()) {

                String key = entry.getKey();
                if (key.equals("sortField") || key.equals("sortRule")) {
                    continue;
                }
                if (key.equals("pageNum")) {
                    continue;
                }
                url += key + "=" + entry.getValue() + "&";

            }
            url = url.substring(0, url.length() - 1);
        }
        return url;

    }
}